﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace Groovy_IM.Protocols.AIM
{
    public class Tools
    {
        public static ushort GetWord(IList<byte> buffer, int offset)
        {
            return (ushort)((buffer[offset] * 256) + buffer[offset + 1]);
        }

        public static ushort GetWord(FLAPSocket packet)
        {
            return (ushort)((packet.Data[packet.Offset++] * 256) + packet.Data[packet.Offset++]);
        }

        public static void PutWord(IList<byte> buffer, int offset, ushort value)
        {
            buffer[offset] = (byte)(value / 256);

            buffer[offset + 1] = (byte)(value % 256);
        }

        public static uint GetDword(IList<byte> buffer, int offset)
        {
            return (uint)((GetWord(buffer, offset) * 65536) + (GetWord(buffer, offset + 2)));
        }

        public static uint GetDword(FLAPSocket packet)
        {
            return (uint)((GetWord(packet) * 65536) + GetWord(packet));
        }

        public static void PutDword(IList<byte> buffer, int offset, uint value)
        {
            PutWord(buffer, offset, (ushort)(value / 65536));

            PutWord(buffer, offset + 2, (ushort)(value % 65536));
        }

        public static ulong GetQword(IList<byte> buffer, int offset)
        {
            return (ulong)((GetDword(buffer, offset) * 4294967296) + GetDword(buffer, offset + 4));
        }

        public static void PutQword(IList<byte> buffer, int offset, ulong value)
        {
            PutDword(buffer, offset, (uint)(value / 4294967296));

            PutDword(buffer, offset + 4, (uint)(value % 4294967296));
        }

        public static byte[] MakeTLV(ushort type, string value)
        {
            byte[] tlv = new byte[4 + value.Length];

            PutWord(tlv, 0, type);

            PutWord(tlv, 2, (ushort)value.Length);

            Encoding.UTF8.GetBytes(value, 0, value.Length, tlv, 4);

            return tlv;
        }

        public static byte[] MakeTLV(ushort type, byte[] value)
        {
            byte[] tlv = new byte[4 + value.Length];

            PutWord(tlv, 0, type);

            PutWord(tlv, 2, (ushort)value.Length);

            Buffer.BlockCopy(value, 0, tlv, 4, value.Length);

            return tlv;
        }
    }
}